from datetime import datetime
from app import db

class MealFood(db.Model):
    __tablename__ = 'meal_foods'

    meal_food_id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 主键
    meal_id = db.Column(db.Integer, db.ForeignKey('meals.meal_id'), nullable=False)  # 关联的餐食ID
    food_id = db.Column(db.Integer, db.ForeignKey('foods.food_id'), nullable=False)  # 关联的食品ID
    meal_num = db.Column(db.Integer)  # 餐次，早1中2晚3加4
    replaced = db.Column(db.Integer, default=0)  # 是否替换，默认为0，发生替换置1
    related_foods = db.Column(db.Text) # 相关食物，如果有替换以队列形式写入，如["菜烩面"]
    quantity = db.Column(db.Float, nullable=False, default=1)  # 每个食品的份数（每份100g，步长50g）
    calories = db.Column(db.Float) # 根据quantity和食物每100g的calories计算得到
    created_at = db.Column(db.DateTime, default=datetime.utcnow)  # 创建时间

    meal = db.relationship('Meal', backref=db.backref('meal_foods', lazy=True))  # 与meals表的关联
    food = db.relationship('Food', backref=db.backref('meal_foods', lazy=True))  # 与foods表的关联

    # to_dict 方法
    def to_dict(self):
        return {
            'meal_food_id': self.meal_food_id,
            'meal_id': self.meal_id,
            'food_id': self.food_id,
            'quantity': self.quantity,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'food': self.food.to_dict() if self.food else None  # 将关联的 food 转换为字典
        }